package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.utils.RedisKeys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    public void saveDish(DishDto dishDto) {
        System.out.println("添加前:"+dishDto.getId());
        //1.添加菜品，获得添加后的菜品ID
        //包含一个功能，添加成功后把添加的主键id 设置到对象中
        save(dishDto);
        //2.取出所有口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //3.为每个口味添加的菜品ID  （外键）
        System.out.println("添加后:"+dishDto.getId());
        Long id = dishDto.getId();
        //4.循环的设置到口味对象中
        /*for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }*/
        flavors.stream().forEach(c->c.setDishId(id));
        //5.保存到数据库中
        dishFlavorService.saveBatch(flavors);
        //6.清空掉此分类的缓存数据
        redisTemplate.delete(RedisKeys.DISH+dishDto.getCategoryId()+"_"+dishDto.getStatus());

    }

    @Autowired
    private CategoryService categoryService;

    @Override
    public Page<DishDto> findByPage(Integer page, Integer pageSize, String name) {

        //1.构建分页条件对象
        Page<Dish> pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Dish> wapper =new LambdaQueryWrapper<>();
        if(null!=name && name != ""){
            //添加模糊查询
            wapper.like(Dish::getName,name);
        }
        //因为新的菜品应该放在前面，所以需要添加一个排序规则
        //Desc 从大到小
        wapper.orderByDesc(Dish::getUpdateTime);
        //分页查询
        Page<Dish> page1 = this.page(pageInfo, wapper);
        //把原有的Dish对象重新封装程一个DishDto 对象
        List<Dish> dishes = page1.getRecords();
        //把List<Dish> 中的所有数据复制到 List<DishDto>
        //BeanUtils.copyProperties(dishes,dishDtos);
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(dishes), DishDto.class);

        for (DishDto dishDto : dishDtos) {
            Long categoryId = dishDto.getCategoryId();//获得分类id
            //根据分类id 查询分类名称
            Category category = categoryService.getById(categoryId);
            //把分类的名字设置给dto对象
            dishDto.setCategoryName(category.getName());
        }
        Page<DishDto> dtoPage = new Page<>();
        dtoPage.setRecords(dishDtos);
        dtoPage.setTotal(page1.getTotal());

        return dtoPage;
    }

    @Override
    public DishDto findDishDtoById(Long id) {
        //1.查询出需要查询的菜品信息，
        Dish dish = this.getById(id);

        //2.根据菜品id查询口味集合
        LambdaQueryWrapper<DishFlavor> wapper = new LambdaQueryWrapper<>();
        wapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(wapper);

        //3.两个数据封装程DishDto
        DishDto dishDto = new DishDto();
        dishDto.setName(dish.getName());
        //如果一行一行的复制，那么效率太低。
        //直接进行一个Bean的拷贝
        //把dish 中的属性复制到dishDto
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateDishDto(DishDto dishDto) {
        //1.dish表中的数据，直接update
        this.updateById(dishDto);

        //2.flover中的数据，先删除后修改  （）
        List<DishFlavor> flavors = dishDto.getFlavors();
        //为每个口味设置菜品ID
        flavors = flavors.stream().map(c->{
            c.setDishId(dishDto.getId());
            return c;
        }).collect(Collectors.toList());
        //增删改 使用 LambdaUpdateWrapper
        LambdaUpdateWrapper<DishFlavor> wapper = new LambdaUpdateWrapper<>();
        wapper.eq(DishFlavor::getDishId,dishDto.getId());
        //2.1 先删除
        dishFlavorService.remove(wapper);
        //2.2 在添加   saveOrUpdateBatch  判断是否存在主键id 如果存在
        dishFlavorService.saveOrUpdateBatch(flavors);

        //2.3 清空掉缓存中的数据
        redisTemplate.delete(RedisKeys.DISH+dishDto.getCategoryId()+"_"+dishDto.getStatus());

    }

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<DishDto> findDishsByCategoryId(Long categoryId,Integer status) {
        //1.获取缓存中的数据
        List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(RedisKeys.DISH+categoryId+"_"+status);
        if(dishDtos == null){
            System.out.println("查询数据库....");
            //缓存中如果没有数据，查询数据库
            //根据分类ID查询出所有的菜品即可
            LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
            wapper.eq(Dish::getCategoryId,categoryId);
            wapper.eq(Dish::getStatus,1);
            List<Dish> list = this.list(wapper);
            //简单的方式直接把 Dish 转换程DishDto
            String string = JSON.toJSONString(list);
            dishDtos = JSON.parseArray(string, DishDto.class);
            //补全 dishDtos 中的数据了
            for (DishDto dishDto : dishDtos) {
                //1.封装口味信息
                LambdaQueryWrapper<DishFlavor> flavorWapper = new LambdaQueryWrapper<>();
                flavorWapper.eq(DishFlavor::getDishId,dishDto.getId());
                List<DishFlavor> flavors = dishFlavorService.list(flavorWapper);
                if(flavors.size()>0){
                    dishDto.setFlavors(flavors);
                }
                //2.封装分类名称
                Category category = categoryService.getById(dishDto.getCategoryId());
                if(category != null){
                    dishDto.setCategoryName(category.getName());
                }
            }
            //查询成功，存储到redis缓存中
            redisTemplate.opsForValue().set(RedisKeys.DISH+categoryId+"_"+status,dishDtos);

            return dishDtos;
        }
        System.out.println("查询redis缓存...");
        return dishDtos;
    }
}